package com.kanche.bigbaby.collection.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.kanche.bigbaby.R;
import com.kanche.bigbaby.collection.StringUtils;
import com.kanche.bigbaby.collection.domain.WordChecker;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import com.kkche.bss.R;
//import com.kkche.bss.collection.domain.WordChecker;
//import com.kkche.bss.dialogs.KancheDialogFragment;
//import com.kkche.bss.utils.StringUtils;

//import com.kkche.merchant.R;
//import com.kkche.merchant.utils.StringUtil;
//import com.kkche.merchant.utils.WordChecker;

/**
 * Created by nealmi on 7/2/14.
 */
public class VehicleDescriptionEditDialog extends KancheDialogFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    private EditText descTxt;
    private Button doneButton;
    private Button clearButton;
    private GridView gridView;
    private String[] contents;
    private onDoneListener listener;
    private String content;
    private WordChecker checker = WordChecker.getInstance();
    private WordChecker.CheckResult result;

    public VehicleDescriptionEditDialog(){
    }

    private void addCheckWord() {
        try {
            InputStream fis = getResources().getAssets().open("wl.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis,
                    Charset.forName("UTF-8")));
            String word = "";
            while ((word = br.readLine()) != null) {
                checker.addWord(word);
            }
            br.close();
            br = null;
            fis = null;
        } catch (Exception e) {
            System.out.println("read file error " + e.getMessage());
        }
    }

    public onDoneListener getListener() {
        return listener;
    }

    public void setListener(onDoneListener listener) {
        this.listener = listener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().setTitle("编辑内容");

        View view = inflater.inflate(R.layout.dialog_vehicle_description_eiditor, container);
        descTxt = (EditText) view.findViewById(R.id.txt_desc);
        descTxt.setText(content);
        doneButton = (Button) view.findViewById(R.id.btn_action_done);
        doneButton.setOnClickListener(this);
        clearButton = (Button) view.findViewById(R.id.btn_action_clear);
        clearButton.setOnClickListener(this);
        gridView = (GridView) view.findViewById(R.id.grid_view);

        String[] labels = getResources().getStringArray(R.array.vehicle_desc_template_labels);
        contents = getResources().getStringArray(R.array.vehicle_desc_template_contents);

        gridView.setAdapter(new MyAdapter(getActivity(), R.layout.vehicle_desc_template_grid_item, labels));
        gridView.setOnItemClickListener(this);
        addCheckWord();
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        if (position == parent.getCount() - 1 && StringUtils.hasText(descTxt.getText().toString())) {
            new AlertDialog.Builder(getActivity())
                    .setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            descTxt.setText(contents[position]);
                        }
                    })
                    .setTitle("提示")
                    .setMessage("您确定要清空内容？")
                    .create().show();

        } else {
            descTxt.setText(contents[position]);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_action_done:
                String desc = descTxt.getEditableText().toString().trim();
                result = checker.check(desc);
                Pattern p= Pattern.compile(getResources().getString(R.string.regula_phonenumber));
                Matcher m=p.matcher(desc);
                if(m.find()){
                    new AlertDialog.Builder(getActivity())
                            .setTitle("温馨提示")
                            .setCancelable(false)
                            .setMessage("你输入的内容中包含联系方式:" + m.group() + "请删除后再继续")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create().show();
                    return;
                }
                if (!StringUtils.isLengthBetween(desc, 15, 500)) {
                    descTxt.setError("请输入至少15个字，最多300个字。");
                    return;
                }
                if(!result.getOk()){
                    String stb = new StringBuffer().append("你的描述中含有敏感词\"").append(desc.substring(result.getOffset(),result.getOffset()+result.getLen())).append("\"请返回修改").toString();
                    new AlertDialog.Builder(getActivity())
                    .setTitle("温馨提示")
                    .setCancelable(false)
                    .setMessage(stb)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).create().show();
                    return;
                }
                if (listener != null) {
                    listener.onDone(desc);
                }
                dismiss();
                break;
            case R.id.btn_action_clear:
                descTxt.getText().clear();
                break;
        }
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }


    public interface onDoneListener {
        void onDone(String content);
    }

    private class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context context, int resource) {
            super(context, resource);
        }

        private MyAdapter(Context context, int resource, String[] objects) {
            super(context, resource, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if (position == getCount() - 1) {
                v.setBackgroundResource(R.drawable.desc_template_grid_item_gray);
            } else {
                v.setBackgroundResource(R.drawable.desc_template_grid_item);
            }
            v.invalidate();
            return v;
        }
    }
}
